package com.haojin.java;

import org.junit.Test;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;

/**
 * @author .29.
 * @create 2022-04-04 19:20
 */
public class JDK8DataTimeTest {
    @Test
    public  void test(){
            /*
    LocalDate  、 LocalTime   、  LocalDataTime的使用
    说明：
    1.LocalDateTime使用频率较高
    2.类似于Calendar,但优化了其缺陷
     */
        //now():获取当前的日期，时间，日期+时间
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();

        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);

        //of():设置指定的年月日时分秒。没有偏移量
        LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 29, 10, 10, 10);
        System.out.println(localDateTime1);

        //getXxx()：获取时间
        System.out.println(localDateTime1.getDayOfMonth());
        System.out.println(localDateTime1.getDayOfWeek());
        System.out.println(localDateTime1.getHour());

        //withXxx()：设置相关属性,体现不可变性
        LocalDateTime localDateTime2 = localDateTime1.withDayOfYear(99);
        System.out.println(localDateTime1.getDayOfYear());
        System.out.println(localDateTime2.getDayOfYear());

    }
        /*
        Instant的使用
         */
    @Test
    public void test2(){
        //now():获取本初子午线的对应的标准时间
        Instant instant = Instant.now();
        System.out.println(instant);
    }

    /*
    DateTimeFormatter:格式化或解析日期，时间
       类似于：SimpleDateFormat
     */
    @Test
    public void test3(){
        //方式一：预定义的标准格式。如：ISO_LOCAL_DATE_TIME等
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //格式化：日期-->字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = dateTimeFormatter.format(localDateTime);
        System.out.println(localDateTime);
        System.out.println(str1);
        //解析：字符串 --> 解析
        TemporalAccessor parse = dateTimeFormatter.parse("2022-04-04T19:56:37.544");
        System.out.println(parse);


        //重点：方式三：自定义的格式
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //解析   .parse
        //格式化 .format
    }
}
